<template>
    <div ref="img" v-bind="[$props, $attrs]" @mouseover="over($event)" @mouseout="out($event)"/>
</template>
<script type="text/ecmascript-6">
    export default {
        name: 'imgHover',
        props: {
            img1: {
                type: String, default() {
                    return ""
                }
            },
            img2: {type: String, default: ""}
        },
        data() {
            return {}
        },
        watch:{
            img1(v){
                this.$refs["img"].style.backgroundImage = "url(" + v + ")";
            }
        },
        mounted() {
            this.$refs["img"].style.backgroundImage = "url(" + this.img1 + ")";
        },
        methods: {
            over(e) {
                if (!this.img2) return;
                var target = e.target;
                target.classList.add("fade-in");
                this.$nextTick(it => {
                    setTimeout(it => {
                        target.style.backgroundImage = 'url(' + this.img2 + ')'
                    }, 100);
                    setTimeout(it => {
                        target.classList.remove("fade-in");
                    }, 200)
                });
            },
            out(e) {
                if (!this.img2) return;
                var target = e.target;
                target.classList.add("fade-out");
                this.$nextTick(it => {
                    setTimeout(it => {
                        target.style.backgroundImage = 'url(' + this.img1 + ')'
                    }, 100);

                    setTimeout(it => {
                        target.classList.remove("fade-out");
                    }, 200)
                });
            }
        }
    }
</script>
<style>
    @keyframes frat {
        0% {
            opacity: 1;
        }
        50% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }
    }

    .fade-in, .fade-out {
        animation: frat 200ms;
    }
</style>